#include <stdio.h>
#include <sys/iosupport.h>
#include <ogcsys.h>
#include <gccore.h>
#include <reent.h>

#include "gecko_console.h"

static const devoptab_t *dotab_console;
int usb_sendbuffer_safe(s32 chn,const void *buffer,int size);
int usb_sendbuffer(s32 chn,const void *buffer,int size);

int __gecko_write(struct _reent *r,int fd,const char *ptr,int len)
{
	char *tmp = (char*)ptr;
	u32 level;
	if(dotab_console)
		dotab_console->write_r(r,fd,ptr,len);
		
	if(!tmp || len<=0) return -1;
	level = IRQ_Disable();
	usb_sendbuffer(1, ptr, len);
	IRQ_Restore(level);
	return len;
}

const devoptab_t dotab_gecko = {
	"stdout",	// device name
 0,			// size of file structure
 NULL,		// device open
 NULL,		// device close
 __gecko_write,	// device write
 NULL,		// device read
 NULL,		// device seek
 NULL,		// device fstat
 NULL,		// device stat
 NULL,		// device link
 NULL,		// device unlink
 NULL,		// device chdir
 NULL,		// device rename
 NULL,		// device mkdir
 0,			// dirStateSize
 NULL,		// device diropen_r
 NULL,		// device dirreset_r
 NULL,		// device dirnext_r
 NULL,		// device dirclose_r
 NULL		// device statvfs_r
};

void gecko_console_init(int chain) {
	dotab_console = NULL;
	if(chain)
		dotab_console = devoptab_list[STD_OUT];
	devoptab_list[STD_OUT] = &dotab_gecko;
	devoptab_list[STD_ERR] = &dotab_gecko;
}

